#include "httpserver.h"

#include <QDebug>
#include <QFile>
#include <QHostAddress>

httpserver::httpserver() {
    server = new QTcpServer(this);

    if(!server->listen(QHostAddress::Any, 8080))
    {
        qDebug() << "Web服务未启动";
    }
    else
    {
        qDebug() << "Web服务在端口8080等待客户端连接";
    }
    //有客户端连接时触发newConnection信号
    connect(server, &QTcpServer::newConnection, this, &httpserver::connection);
}

void httpserver::connection()
{
    //取出建立好连接的套接字
    QTcpSocket *socket = server->nextPendingConnection();

    //获取对方的IP和端口
    QHostAddress clientIp = socket->peerAddress();//客户端的IP
    qint16 port = socket->peerPort();//客户端的端口


    if(tcpSktList.contains(socket))
    {
        qDebug()<<QString("%1:%2的连接早已建立过").arg(clientIp.toString()).arg(port);
    }
    else
    {
        qDebug()<<QString("新的连接已建立 %1:%2").arg(clientIp.toString()).arg(port);
        tcpSktList.append(socket);//记录下客户端发起的连接
        connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));//客户端掉线处理
        connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));//客户端发来的数据处理
    }
}

void httpserver::onReadyRead()
{
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());

    if(socket)
    {
        //从通信套接字中取出内容
        QByteArray array = socket->readAll();
        QString request = QString::fromUtf8(array);
        qDebug() << "正在从浏览器读取数据= " << request;//打印收到的来自客户端的消息

        if(request.startsWith("GET"))//如果是GET请求
        {
            QFile file("index.txt");
            if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                qDebug() << "文件打开失败";
                return;
            }
            QString tempStr = "";//临时字符串
            while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
            {
                //tempStr = file.readLine();  //读取文件中一行
                tempStr = file.readAll();   //读取文件中所有内容
                //qDebug() <<"tempStr = "<<tempStr;
            }

            char *ch = tempStr.toLatin1().data();

            socket->write("HTTP/1.1 200 OK\r\n");
            socket->write("Content-Type: text/html\r\n");
            socket->write("\r\n");
            socket->write(ch);
            socket->flush();
        }
    }
}

void httpserver::onDisconnected()
{
    QTcpSocket *socket = static_cast<QTcpSocket *>(sender());
    //获取对方的IP和端口
    QHostAddress clientIp = socket->peerAddress();//客户端的IP
    qint16 port = socket->peerPort();//客户端的端口
    qDebug()<<QString("客户端掉线 %1:%2").arg(clientIp.toString()).arg(port);

    tcpSktList.removeOne(socket);
}

